package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.factory.MarketingFieldHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.vo.AfterSaveVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.service.CouponTempleteService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.MarketingTokenUtil;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.MarketingErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.listbatch.pojo.dto.OnlineDTO;
import com.xbongbong.pro.log.pojo.DetailLogPojo;
import com.xbongbong.pro.marketing.pojo.dto.MarketingManagementDataAddDTO;
import com.xbongbong.pro.marketing.pojo.dto.MarketingManagementDataUpdateDTO;
import com.xbongbong.pro.marketing.pojo.dto.MarketingManagementDeleteBatchDTO;
import com.xbongbong.pro.marketing.pojo.dto.MarketingValidateDataDTO;
import com.xbongbong.pro.marketing.pojo.vo.MarketingManagementDeleteBatchVO;
import com.xbongbong.pro.message.constant.MarketingManagementPushConstant;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.DistributorMessageRabbitMqDTO;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.rabbitmq.producer.BaseProducer;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.CouponEntity;
import com.xbongbong.saas.domain.entity.CouponTempleteEntity;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.FullDiscountCouponEnum;
import com.xbongbong.saas.enums.business.MarketingBaseEnum;
import com.xbongbong.saas.enums.dictionary.CouponNumTypeEnum;
import com.xbongbong.saas.enums.dictionary.InapplicableProductTypeEnum;
import com.xbongbong.saas.enums.dictionary.LaunchChannelTypeEnum;
import com.xbongbong.saas.enums.dictionary.MarketingStatusEnum;
import com.xbongbong.saas.enums.dictionary.ValidityTypeEnum;
import com.xbongbong.saas.help.MarketingHelp;
import com.xbongbong.saas.help.SaasSaveHelp;
import com.xbongbong.saas.help.SaasUpdateHelp;
import com.xbongbong.saas.model.CouponTempleteModel;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author jyh
 * @version v1.0
 * @date 2020/12/24 12:21
 * @since v1.0
 */
@Service("CouponTempleteService")
public class CouponTempleteServiceImpl implements CouponTempleteService {


    private static final Logger LOG = LoggerFactory.getLogger(CouponTempleteServiceImpl.class);


    @Resource
    private CouponTempleteModel couponTempleteModel;
    @Resource
    private SaasUpdateHelp saasUpdateHelp;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private LogHelp logHelp;
    @Resource
    private MarketingFieldHelp marketingFieldHelp;
    @Resource
    private SaasSaveHelp saasSaveHelp;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private BaseProducer baseProducer;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;
    @Resource
    private UserModel userModel;
    @Resource
    private MarketingHelp marketingHelp;


    @Override
    public void beforeSave(MarketingValidateDataDTO marketingValidateDataDTO) throws XbbException {

        JSONObject data = marketingValidateDataDTO.getDataList();
        String corpid = marketingValidateDataDTO.getCorpid();
        if (Objects.equals(data.getString(FullDiscountCouponEnum.INAPPLICABLE_PRODUCT_TYPE.getAttr()), InapplicableProductTypeEnum.FIXED_PRODUCT.getCode())) {
            JSONArray inApplicableProduct = data.getJSONArray(MarketingBaseEnum.INAPPLICABLE_PRODUCT.getAttr());
            if (!CollectionUtils.isEmpty(inApplicableProduct)) {
                saasSaveHelp.formatProductSave(data, MarketingBaseEnum.INAPPLICABLE_PRODUCT.getAttr());
            } else {
                throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500011);
            }
        }
        //领取后多少天数不可用要小于领取后多少天有效
        if (Objects.equals(data.getString(MarketingBaseEnum.VALIDITY_TYPE.getAttr()), ValidityTypeEnum.RELATIVE_DATE.getCode())) {
            if (Objects.isNull(data.getInteger(MarketingBaseEnum.VALIDITY_DAYS.getAttr())) || Objects.isNull(data.getInteger(MarketingBaseEnum.FORBID_DAYS.getAttr()))) {
                throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500016);
            }
            if (data.getInteger(MarketingBaseEnum.VALIDITY_DAYS.getAttr()) < data.getInteger(MarketingBaseEnum.FORBID_DAYS.getAttr())) {
               throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500007);
            }
        }
        JSONArray launchChannel = data.getJSONArray(MarketingBaseEnum.LAUNCH_CHANNEL.getAttr());
        if (CollectionUtils.isEmpty(launchChannel)) {
            throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500012);
        }
        for (int i = 0; i < launchChannel.size(); i++) {
            if (Objects.equals(launchChannel.getInteger(i), LaunchChannelTypeEnum.COPY_INSTRUCTION_DELIVERY.getCode())) {
                String instructionCode = MarketingTokenUtil.getEncryptToken(corpid, marketingValidateDataDTO.getBusinessType());
                data.put(MarketingBaseEnum.HASH_CODE.getAttr(), instructionCode);
                break;
            }
        }
    }

    @Override
    public AfterSaveVO insert(MarketingManagementDataAddDTO marketingManagementDTO) throws XbbException {
        AfterSaveVO afterSaveVO = new AfterSaveVO();
        Integer businessType = marketingManagementDTO.getBusinessType();
        JSONObject data = marketingManagementDTO.getDataList();
        String corpid = marketingManagementDTO.getCorpid();
        String userId = marketingManagementDTO.getUserId();
        String userName = marketingManagementDTO.getLoginUserName();
        CouponTempleteEntity couponTempleteEntity = new CouponTempleteEntity();
        data.put(MarketingBaseEnum.USED_NUM.getAttr(), BasicConstant.ZERO);
        data.put(MarketingBaseEnum.GET_NUM.getAttr(), BasicConstant.ZERO);
        data.put(MarketingBaseEnum.STATUS.getAttr(), MarketingStatusEnum.WAIT_ONLINE.getCode());
        data.put(MarketingBaseEnum.TYPE.getAttr(), businessType);
        //-1代表不限制发放数量
        couponTempleteEntity.setCouponNum(-1);
        if (Objects.equals(data.getString(MarketingBaseEnum.COUPON_NUM_TYPE.getAttr()), CouponNumTypeEnum.CUSTOM.getCode())) {
            couponTempleteEntity.setCouponNum(FastJsonHelper.getIntegerOrDefaultFromFormData(data, FullDiscountCouponEnum.NUM.getAttr(), 0));
        }
        couponTempleteEntity.setName(data.getString(MarketingBaseEnum.NAME.getAttr()));
        couponTempleteEntity.setCorpid(corpid);
        couponTempleteEntity.setData(data);
        couponTempleteEntity.setStatus(MarketingStatusEnum.WAIT_ONLINE.getCode());
        couponTempleteEntity.setBusinessType(businessType);
        couponTempleteEntity.setBeginTime(data.getLong(MarketingBaseEnum.BEGIN_TIME.getAttr()));
        couponTempleteEntity.setEndTime(data.getLong(MarketingBaseEnum.END_TIME.getAttr()));
        couponTempleteEntity.setCreatorId(marketingManagementDTO.getUserId());
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getCode(), corpid, DistributorMarkEnum.DISTRIBUTOR.getCode(), null);
        couponTempleteEntity.setFormId(paasFormEntityExt.getId());
        couponTempleteModel.insert(couponTempleteEntity);
        String logName = couponTempleteEntity.getName();
        OperateTypeEnum operateTypeEnum = OperateTypeEnum.NEW;
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(),logName);
        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.MARKETING_ACTIVITY_MANAGEMENT, operateTypeEnum,
                couponTempleteEntity.getId().toString(), logName, memo, marketingManagementDTO.getHttpHeader());
        afterSaveVO.setFormDataId(couponTempleteEntity.getId());
        return afterSaveVO;
    }

    @Override
    public AfterSaveVO update(MarketingManagementDataUpdateDTO marketingManagementDTO) throws XbbException {
        AfterSaveVO afterSaveVO = new AfterSaveVO();
        JSONObject data = marketingManagementDTO.getDataList();
        String corpid = marketingManagementDTO.getCorpid();
        Integer businessType = marketingManagementDTO.getBusinessType();
        MarketingValidateDataDTO marketingValidateDataDTO =  new MarketingValidateDataDTO();
        marketingValidateDataDTO.setIsEdit(true);
        BeanUtil.copyProperties(marketingManagementDTO, marketingValidateDataDTO);
        beforeSave(marketingValidateDataDTO);
        CouponTempleteEntity couponTempleteEntity = new CouponTempleteEntity();
        Long dataId = marketingManagementDTO.getDataId();
        CouponTempleteEntity oldCoupounTemplete = couponTempleteModel.getByKey(dataId, corpid);
        if (!Objects.equals(oldCoupounTemplete.getStatus(), MarketingStatusEnum.WAIT_ONLINE.getCode())) {
            throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500009);
        }
        data.put(MarketingBaseEnum.USED_NUM.getAttr(), BasicConstant.ZERO);
        data.put(MarketingBaseEnum.GET_NUM.getAttr(), BasicConstant.ZERO);
        data.put(MarketingBaseEnum.TYPE.getAttr(), businessType);
        data.put(MarketingBaseEnum.STATUS.getAttr(), MarketingStatusEnum.WAIT_ONLINE.getCode());

        //-1代表不限制发放数量
        couponTempleteEntity.setCouponNum(-1);
        if (Objects.equals(data.getString(MarketingBaseEnum.COUPON_NUM_TYPE.getAttr()), CouponNumTypeEnum.CUSTOM.getCode())) {
            couponTempleteEntity.setCouponNum(FastJsonHelper.getIntegerOrDefaultFromFormData(data, FullDiscountCouponEnum.NUM.getAttr(), 0));
        }
        couponTempleteEntity.setCorpid(corpid);
        couponTempleteEntity.setName(data.getString(MarketingBaseEnum.NAME.getAttr()));
        couponTempleteEntity.setData(data);
        couponTempleteEntity.setBusinessType(businessType);
        couponTempleteEntity.setBeginTime(data.getLong(MarketingBaseEnum.BEGIN_TIME.getAttr()));
        couponTempleteEntity.setEndTime(data.getLong(MarketingBaseEnum.END_TIME.getAttr()));
        couponTempleteEntity.setGetNum(BasicConstant.ZERO);
        couponTempleteEntity.setUsedNum(BasicConstant.ZERO);
        couponTempleteEntity.setId(dataId);
        couponTempleteEntity.setStatus(MarketingStatusEnum.WAIT_ONLINE.getCode());
        couponTempleteModel.update(couponTempleteEntity);
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        String userName = marketingManagementDTO.getLoginUserName();
        String logName = couponTempleteEntity.getName();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        JSONObject oldObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(oldCoupounTemplete));
        JSONObject newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(couponTempleteEntity));
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_WORK),userName, xbbRefTypeEnum.getName(),logName);
        List<DetailLogPojo> detailArr = logHelp.getDetailArr4Data(corpid, redundantTemplateTypeEnum, marketingFieldHelp.getFieldMapByBusinessType(businessType), oldObj, newObj);
        mongoLogHelp.buildLog4DetailArr(detailArr, corpid, marketingManagementDTO.getUserId(), userName, OperateModuleTypeEnum.MARKETING_ACTIVITY_MANAGEMENT, OperateTypeEnum.EDIT,
               dataId.toString(), couponTempleteEntity.getName(), memo, marketingManagementDTO.getHttpHeader());
        afterSaveVO.setFormDataId(couponTempleteEntity.getId());
        return afterSaveVO;
    }

    @Override
    public MarketingManagementDeleteBatchVO deleteBatch(MarketingManagementDeleteBatchDTO marketingManagementDeleteBatchDTO) throws XbbException {
        MarketingManagementDeleteBatchVO marketingManagementDeleteBatchVO = new MarketingManagementDeleteBatchVO();
        List<Long> dataIdList = marketingManagementDeleteBatchDTO.getDataIdList();
        String corpid = marketingManagementDeleteBatchDTO.getCorpid();
        if (Objects.equals(dataIdList.size(), BasicConstant.ONE)) {
            Long id = dataIdList.get(0);
            CouponTempleteEntity couponTempleteEntity = couponTempleteModel.getByKey(id, corpid);
            if (!Objects.equals(couponTempleteEntity.getStatus(), MarketingStatusEnum.WAIT_ONLINE.getCode())) {
                throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500006);
            }
            couponTempleteModel.deleteByKey(id, corpid);
            String userName = marketingManagementDeleteBatchDTO.getLoginUserName();
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(couponTempleteEntity.getBusinessType());
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_WORK), userName, xbbRefTypeEnum.getName(), couponTempleteEntity.getName());
            mongoLogHelp.buildLog(corpid, marketingManagementDeleteBatchDTO.getUserId(), userName, OperateModuleTypeEnum.MARKETING_ACTIVITY_MANAGEMENT, OperateTypeEnum.DELETE,
                    couponTempleteEntity.getId().toString(), couponTempleteEntity.getName(), memo, marketingManagementDeleteBatchDTO.getHttpHeader());
        }
        marketingManagementDeleteBatchVO.setDeleteIds(dataIdList);
        return marketingManagementDeleteBatchVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void online(OnlineDTO onlineDTO) throws XbbException {
        String corpid = onlineDTO.getCorpid();
        List<Long> dataIdList = onlineDTO.getDataIdList();
        Long dataId = dataIdList.get(0);
        // 上下架 1上架0下架
        Integer online = onlineDTO.getOnline();
        if (Objects.equals(online, 1) && !onlineDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.MARKETING_ACTIVITY_ON.getAlias())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100050.getCode(), String.format(SystemErrorCodeEnum.API_ERROR_100050.getMsg(), ProPermissionAliasEnum.MARKETING_ACTIVITY_ON.getMemo()));
        }else if (Objects.equals(online, 0) && !onlineDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.MARKETING_ACTIVITY_OFF.getAlias())){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100050.getCode(), String.format(SystemErrorCodeEnum.API_ERROR_100050.getMsg(), ProPermissionAliasEnum.MARKETING_ACTIVITY_OFF.getMemo()));
        }
        CouponTempleteEntity couponTempleteEntity = couponTempleteModel.getByKey(dataId, corpid);
        String key = corpid + "_" + dataId;
        //上下架日志
        String userId = onlineDTO.getUserId();
        String userName = onlineDTO.getLoginUserName();
        try {
            Long incrNum = paasRedisHelper.getIncrNum(RedisPrefixConstant.MARKETING_ONLINE_KEY, key, TimeConstant.SECONDS_PER_MINUTE, 1, 1);
            if (incrNum > 1) {
                throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500034);
            }
            long now = DateTimeUtil.getInt();
            Long endTime = couponTempleteEntity.getEndTime();
            JSONObject data = couponTempleteEntity.getData();
            if ((Objects.equals(online, BasicConstant.ONE))) {
                //判断活动是否下架，下架的不能在上架
                if (Objects.equals(couponTempleteEntity.getStatus(), MarketingStatusEnum.OFFLINE.getCode())) {
                    throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500033);
                }
                //同时上架的活动不能超过100个
                Integer couponCount = couponTempleteModel.getOnlineCouponCount(corpid);
                if (couponCount >= BasicConstant.COUPON_MAX_COUNT) {
                    throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500031);
                }
                //判断活动是否过期
                if (endTime < DateTimeUtil.getTodayInt()) {
                    throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500032);
                }
                Integer expireTime = Math.toIntExact(endTime + TimeConstant.SECONDS_PER_DAY - now) + 3 * TimeConstant.SECONDS_PER_DAY;
                paasRedisHelper.setValue(RedisPrefixConstant.COUPON_NUM_KEY, key, couponTempleteEntity.getCouponNum(), expireTime);
                couponTempleteEntity.setStatus(MarketingStatusEnum.ONLINE.getCode());
                data.put(MarketingBaseEnum.STATUS.getAttr(),MarketingStatusEnum.ONLINE.getCode());
            }else if ((Objects.equals(online, BasicConstant.ZERO))){
                //下架移除
                String value = Objects.isNull(paasRedisHelper.getValue(RedisPrefixConstant.COUPON_NUM_KEY, key)) ? "0" : paasRedisHelper.getValue(RedisPrefixConstant.COUPON_NUM_KEY, key);
                couponTempleteEntity.setGetNum(couponTempleteEntity.getCouponNum() - Integer.parseInt(value));
                paasRedisHelper.removeValue(RedisPrefixConstant.COUPON_NUM_KEY, key);
                couponTempleteEntity.setStatus(MarketingStatusEnum.OFFLINE.getCode());
                data.put(MarketingBaseEnum.STATUS.getAttr(),MarketingStatusEnum.OFFLINE.getCode());
            }
            couponTempleteModel.update(couponTempleteEntity);
            OperateTypeEnum operateTypeEnum = Objects.equals(online, 1) ? OperateTypeEnum.ONLINE : OperateTypeEnum.OFFLINE;
            String onlyOnline = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ONLINE), userName, XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getName(), couponTempleteEntity.getName());
            String onlyOffline = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_OFFLINE), userName, XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getName(), couponTempleteEntity.getName());
            String memo = Objects.equals(online, 1) ? onlyOnline : onlyOffline;
            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.MARKETING_ACTIVITY_MANAGEMENT, operateTypeEnum,
                    couponTempleteEntity.getId().toString(), couponTempleteEntity.getName(), memo, onlineDTO.getHttpHeader());
            paasRedisHelper.removeValue(RedisPrefixConstant.MARKETING_ONLINE_KEY, key);
        } catch (XbbException e) {
            paasRedisHelper.removeValue(RedisPrefixConstant.COUPON_NUM_KEY, key);
            paasRedisHelper.removeValue(RedisPrefixConstant.MARKETING_ONLINE_KEY, key);
            throw e;
        } catch (Exception e) {
            paasRedisHelper.removeValue(RedisPrefixConstant.COUPON_NUM_KEY, key);
            paasRedisHelper.removeValue(RedisPrefixConstant.MARKETING_ONLINE_KEY, key);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(),SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        if ((Objects.equals(online, BasicConstant.ONE))) {
            Runnable runnable = () -> {
                UserEntity creator = userModel.getByKey(userId, corpid);
                PaasFormEntityExt paasFormDataEntity = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getCode(), corpid, DistributorMarkEnum.DISTRIBUTOR.getCode(), null);

                //创建信息
                try {
                    // 上架成功提醒超管，老板 消息推送 系统默认超管老板roleId=1，2?
                    List<UserEntity> managers = userModel.getUsersByRoleId(corpid, Arrays.asList(1,2));
                    List<String> userIdList = new ArrayList<>();
                    for (UserEntity manager : managers) {
                        userIdList.add(manager.getUserId());
                    }

                    userIdList.add(couponTempleteEntity.getCreatorId());
                    PushRefTypePojo.Options options = new PushRefTypePojo.Options(paasFormDataEntity.getAppId(), paasFormDataEntity.getMenuId(),
                            paasFormDataEntity.getId(), dataId, Collections.singletonList(dataId), SaasMarkEnum.SAAS.getCode(),
                            onlineDTO.getBusinessType(),onlineDTO.getBusinessType());
                    MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, userIdList, Collections.singletonList(dataId), 0,
                            null, I18nMessageUtil.getMessage(MarketingManagementPushConstant.MARKETING_ACTIVITY_MANAGEMENT_ONLINE_PUSH_TITLE), String.format(I18nMessageUtil.getMessage(MarketingManagementPushConstant.MARKETING_ACTIVITY_MANAGEMENT_ONLINE_PUSH_CONTENT),
                            creator.getName(),couponTempleteEntity.getName()), null, options);
                    baseProducer.sendMessage(PushTypeEnum.MARKETING_ACTIVITY_MANAGEMENT_ONLINE_PUSH, messageRabbitMqDTO);
                } catch (Exception e) {
                    LOG.error("优惠券上架消息推送", e);
                }

                //创建信息
                try {
                    JSONObject data = couponTempleteEntity.getData();
                    List<String> userIdList = marketingHelp.getPushUserIds(data, corpid);
                    PushRefTypePojo.Options options = new PushRefTypePojo.Options(paasFormDataEntity.getAppId(), paasFormDataEntity.getMenuId(),
                            paasFormDataEntity.getId(), dataId, Collections.singletonList(dataId), SaasMarkEnum.SAAS.getCode(),
                            onlineDTO.getBusinessType(),onlineDTO.getBusinessType());
                    DistributorMessageRabbitMqDTO distributorMessageRabbitMqDTO = new DistributorMessageRabbitMqDTO(corpid, userIdList, Collections.singletonList(dataId), 0,
                            null, I18nMessageUtil.getMessage(MarketingManagementPushConstant.DISTRIBUTOR_MARKETING_ACTIVITY_MANAGEMENT_ONLINE_PUSH_TITLE), String.format(I18nMessageUtil.getMessage(MarketingManagementPushConstant.DISTRIBUTOR_MARKETING_ACTIVITY_MANAGEMENT_ONLINE_PUSH_CONTENT),
                            couponTempleteEntity.getName()), null, options, DistributorMarkEnum.DISTRIBUTOR.getCode());
                    baseProducer.sendMessage(PushTypeEnum.DISTRIBUTOR_MARKETING_ACTIVITY_MANAGEMENT_ONLINE_PUSH, distributorMessageRabbitMqDTO);
                } catch (Exception e) {
                    LOG.error("经销商端优惠券上架消息推送", e);
                }
            };
            threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
        }
    }

    @Override
    public AfterSaveVO add(MarketingManagementDataAddDTO marketingManagementDTO) throws XbbException {
        MarketingValidateDataDTO marketingValidateDataDTO =  new MarketingValidateDataDTO();
        marketingValidateDataDTO.setIsEdit(false);
        BeanUtil.copyProperties(marketingManagementDTO, marketingValidateDataDTO);
        beforeSave(marketingValidateDataDTO);
        AfterSaveVO afterSaveVO = insert(marketingManagementDTO);
        return afterSaveVO;
    }

    @Override
    public void updateUseNum(List<CouponEntity> couponEntityList, String corpid) throws XbbException {
        Map<Long, CouponTempleteEntity> couponTempleteMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<CouponTempleteEntity> updateList = new ArrayList<>();
        long now = DateUtil.getInt();
        for (CouponEntity couponEntity : couponEntityList) {
            CouponTempleteEntity couponTempleteEntity = couponTempleteMap.getOrDefault(couponEntity.getTempleteId(), new CouponTempleteEntity());
            couponTempleteEntity.setCorpid(corpid);
            couponTempleteEntity.setUpdateTime(now);
            couponTempleteEntity.setId(couponEntity.getTempleteId());
            Integer usedNum = Objects.isNull(couponTempleteEntity.getUsedNum()) ? 1 :  couponTempleteEntity.getUsedNum() + 1;
            couponTempleteEntity.setUsedNum(usedNum);
            couponTempleteMap.put(couponEntity.getTempleteId(), couponTempleteEntity);
        }
        for (CouponTempleteEntity value : couponTempleteMap.values()) {
            updateList.add(value);
        }
        couponTempleteModel.updateUsedNum(couponTempleteMap.keySet(), updateList, corpid);
    }


}
